<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商城主页面</title>
    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.4/dayjs.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/home.css"/>
</head>
<body>
<div id="root">

</div>
<script type="text/babel">
    const datas = [
        {
            createTime: 1620023818183,
            id: "1389106691294900226",
            imgPath: "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBw",
            name: "<span className='title' style='color:red'>Java</span>微服务架构实战(SpringBoot+SpringCloud+Docker+ <span className='title' style='color:red'>Java</span>微服务架构实战(SpringBoot+SpringCloud+Docker+",
            price: "￥43.60",
            sku: 65137048523
        },
        {
            createTime: 1620023818183,
            id: "1389106691294900227",
            imgPath: "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBw",
            name: "<span className='title' style='color:red'>Java</span>微服务架构实战(SpringBoot+SpringCloud+Docker+ <span className='title' style='color:red'>Java</span>微服务架构实战(SpringBoot+SpringCloud+Docker+",
            price: "￥43.60",
            sku: 65137048523
        }
    ]
    class Header extends React.Component{
        state = {
            keywords : "",
            carNum : 1,
            datasource : [],
            currentPage: 1,
            pages:0,
            isLogin:false,
            user:{}
        }
        componentDidMount(){
            this.getdata();
            this.userCheck();
        }
        userCheck = ()=>{
            if(localStorage.getItem("user")){
                let user = localStorage.getItem("user");
                user = JSON.parse(user);
                this.setState(()=>{
                    return {isLogin: true,user:user}
                })
            }
        }
        getdata = (page = 1,pageSize = 10)=>{
            axios.get(`http://127.0.0.1:2021/shopstore/good/selectallgoods/${page}/${pageSize}`,{
                headers: {
                    'token': JSON.parse(localStorage.getItem('token')),
                    'userId': JSON.parse(localStorage.getItem('user')).userId
                }
            }).then((resp)=>{
                if(resp.data.status === 200){
                    this.setState(()=>{
                        return {
                            datasource:resp.data.list.records,
                            currentPage: resp.data.list.current,
                            pages:resp.data.list.pages
                        }
                    })
                }else if(resp.data.status === 403){
                    alert(resp.data.message);
                    window.location.href="login.html";
                }
            }).catch((error)=>{
                alert("超时")
            })
        }
        inputHandler = ()=>{
            this.setState(()=>{
                return {keywords: this.inputRef.value}
            })
        }
        //模糊搜索
        search = (current=1,pagesize=10)=>{
            const { keywords } = this.state;
            //状态keyword为""，请求全部数据
            if(keywords === ""){
                axios.get(`http://127.0.0.1:2021/shopstore/good/selectallgoods/1/${pagesize}`,{
                    headers: {
                        'token': JSON.parse(localStorage.getItem('token')),
                        'userId': JSON.parse(localStorage.getItem('user')).userId
                    }
                }).then((resp)=>{
                    if(resp.data.status === 200){
                        this.setState(
                            {
                                datasource:resp.data.list.records,
                                currentPage: resp.data.list.current,
                                pages:resp.data.list.pages
                            }
                        )
                    }else if(resp.data.status === 403){
                        alert(resp.data.message);
                        window.location.href="login.html";
                    }
                }).catch((error)=>{
                    alert("超时")
                })
            }else{
                //不为空，按关键字查找
                axios.get(`http://127.0.0.1:2021/shopstore/good/getgoodsByKeyWord/${keywords}/1/${pagesize}`,{
                    headers: {
                        'token': JSON.parse(localStorage.getItem('token')),
                        'userId': JSON.parse(localStorage.getItem('user')).userId
                    }
                }).then((resp)=>{
                    if(resp.data.status === 200){
                        this.setState(
                            {
                                datasource:resp.data.list.records,
                                currentPage: resp.data.list.current,
                                pages:resp.data.list.pages
                            }
                        )
                    }else if(resp.data.status === 403){
                        alert(resp.data.message);
                        window.location.href="login.html";
                    }
                }).catch((error)=>{
                    alert("超时")
                })
            }
        }
        //添加购物车
        addCar = (data)=>{
            return ()=>{
                data.carNum = this.state.carNum;
                if(window.confirm("确认加入购物车?")){
                    //此处写加入购物车的业务逻辑
                    const car = {
                        'carUserId':JSON.parse(localStorage.getItem("user")).userId,
                        'carGoodId':data.goodId,
                        'carNum':Number(data.carNum)
                    }
                    axios.post(`http://127.0.0.1:2021/shopstore/car/addCar`,car,{
                        headers: {
                            'token': JSON.parse(localStorage.getItem('token')),
                            'userId': JSON.parse(localStorage.getItem('user')).userId
                        }
                    }).then((resp)=>{
                        if(resp.data.status === 200){
                            alert(resp.data.msg);
                            //添加成功初始化状态
                            this.setState({
                                'carNum':1
                            })
                        }else if(resp.data.status === 403){
                            //身份校验失败，打回登录界面
                            alert(resp.data.message);
                            window.location.href="login.html";
                        } else{
                            alert(resp.data.msg);
                        }
                    })
                }
            }
        }
        //页面跳转
        jumpToPage = (data)=>{
            return ()=>{
                this.getdata(data);
            }
        }
        tips = ()=>{
            window.alert("请登陆之后再来操作!")
        }
        layOut = ()=>{
            if(confirm("退出?")){
                localStorage.clear();
                window.location.href="login.html"
            }
        }
        render(){
            const { datasource,user } = this.state;
            return (
                <div className="all">
                    <header className="head">
                        <span className="welcome">{this.state.isLogin?'欢迎用户:'+user.userName+'登录':<a href="login.html">登录</a>}</span>
                        <button style={{cursor:'pointer'}} onClick={this.state.isLogin?this.layOut:this.tips}>退出系统</button>
                    </header>
                    <div className="header">
                        <div className="input-div">
                            <input onChange={this.inputHandler} type="text" placeholder="keywords" ref={(e)=>{this.inputRef = e}}/>
                            <button onClick={this.state.isLogin?this.search:this.tips} className="search-button">搜索</button>
                        </div>
                        <div className="myCar">
                            <button onClick={this.state.isLogin?()=>{window.location.href="./iframe/myCar.html"}:this.tips}>我的购物车</button>
                        </div>
                    </div>
                    <div className="datashow">
                        <ul className="wragall">
                            {
                                datasource.map((item)=>{
                                    return (
                                        <li className="item" key={item.goodId}>
                                            <div className="item-img">
                                                <img src={`data:image/jpeg;base64,${item.goodImgPath}`} alt=".."/>
                                            </div>
                                            <div className="item-price">
                                                {item.goodPrice}
                                            </div>
                                            <div dangerouslySetInnerHTML={{__html:item.goodName}} className="item-name">

                                            </div>
                                            <div className="item-createtime">
                                                {dayjs(item.goodCreateTime).format('YYYY-MM-DD HH:mm:ss')}
                                            </div>
                                            <div className="item-saler">
                                                商家:{item.goodSaler}
                                            </div>
                                            <div className="item-car">
                                                <input min={1} onChange={(e)=>{this.setState({carNum:Number(e.target.value)})}} className="car-input" type="number" defaultValue="1"/>
                                                <button className="car-button" onClick={this.state.isLogin?this.addCar(item):this.tips}>加入购物车</button>
                                            </div>
                                        </li>
                                    )
                                })
                            }
                            <div className="page">
                                {
                                    this.state.currentPage < 2 ? null:<button className="pre-page" onClick={this.jumpToPage(this.state.currentPage - 1)}>上一页</button>
                                }
                                <span className="page-all">
                                    {
                                        new Array(this.state.pages).fill('').map((item,index)=>{
                                            return (
                                                this.state.currentPage === (index+1)?
                                                    <button key={index} className="page-num" style={{backgroundColor:'red',color:'white',fontWeight:600}} onClick={this.jumpToPage(index+1)}>{index+1}</button>:
                                                    <button key={index} className="page-num" onClick={this.jumpToPage(index+1)}>{index+1}</button>
                                            )
                                        })
                                    }
                                </span>
                                {
                                    this.state.currentPage >= this.state.pages ? null:<button className="post-page" onClick={this.jumpToPage(this.state.currentPage + 1)}>下一页</button>
                                }
                            </div>
                        </ul>
                    </div>
                </div>
            )
        }
    }
    ReactDOM.render(
        <div>
            <Header/>
        </div>,document.getElementById("root"));
</script>
</body>
</html>